<template>
  <!-- 优惠券列表 -->
  <a-card :bordered="false">
    <div class="flex-x-sb flex-y-center" style="margin-bottom: 16px">
      <a-radio-group @change="clickTab" v-model="queryParam.status">
        <a-radio-button :value="-1"> 全部 </a-radio-button>
        <a-radio-button :value="0"> 未开始 </a-radio-button>
        <a-radio-button :value="1"> 进行中 </a-radio-button>
        <a-radio-button :value="2"> 已结束 </a-radio-button>
      </a-radio-group>
      <div class="table-operator" style="margin: 0">
        <a-button type="primary" @click="onAdd" icon="plus">新建</a-button>
        <a-popconfirm title="确认删除所选项吗？" @confirm="handleMenuClick">
          <a-button> 批量删除 </a-button>
        </a-popconfirm>
      </div>
    </div>

    <div v-show="selectedRowKeys.length" class="select-title" style="margin-bottom: 16px">
      <a-alert :message="`已选择 ${selectedRowKeys.length} 项`" type="info" show-icon />
    </div>

    <s-table
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      rowKey="id"
      size="default"
      :columns="columns"
      :data="loadData"
      ref="table"
    >
      <a-popconfirm
        placement="topLeft"
        slot="status"
        slot-scope="text, record"
        ok-text="确定"
        cancel-text="取消"
        @confirm="changeShow(record)"
      >
        <template slot="title">
          <p>{{ text == 1 ? '是否确定不显示' : '是否确定显示' }}</p>
        </template>
        <a-tag :color="text == 1 ? 'blue' : 'red'">{{ text | statusFilter }}</a-tag>
      </a-popconfirm>
      <!-- 最低消费金额 -->
      <span slot="min_price" slot-scope="text"> {{ text }}元 </span>

      <!-- 优惠券金额 -->
      <span slot="sub_price" slot-scope="text">{{ text }}元</span>

      <!-- 折扣率 -->
      <span slot="discount" slot-scope="text">{{ text }}折</span>

      <!-- 已领 -->
      <div slot="total_count" slot-scope="text, item">
        <span>{{ item.receive_count }}</span>
      </div>

      <!-- 剩余 -->
      <div slot="surplus_count" slot-scope="text">
        <span v-if="text > 0">{{ text }}</span>
        <span v-else>无限制</span>
      </div>

      <!-- 有效期 -->
      <div slot="expire_type" slot-scope="text, item">
        <span v-if="item.expire_type == 1 && item.expire_day != 0"> 领卷后当日起{{ item.expire_day }}天内可用 </span>
        <span v-else-if="item.expire_type == 1 && item.expire_day == 0">永久生效</span>
        <span v-if="item.expire_type == 2">{{ item.begin_time }}至{{ item.end_time }}</span>
      </div>

      <!-- 优惠卷数量 -->
      <div slot="coupon_status" slot-scope="text">
        <div v-if="text == 0" class="coupon-status-1">未开始</div>
        <div v-if="text == 1" class="coupon-status-1">进行中</div>
        <div v-if="text == 2" class="coupon-status-2">已结束</div>
      </div>

      <div slot="is_join" slot-scope="is_join, item">
        <a-switch
          @click="switchChange($event, item)"
          checked-children="开"
          un-checked-children="关"
          :defaultChecked="is_join == 2 ? true : false"
        />
      </div>

      <!-- 操作按钮 -->
      <span slot="action" slot-scope="text, record">
        <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
        <a-divider type="vertical" />
        <a-dropdown>
          <a class="ant-dropdown-link" @click="e => e.preventDefault()"> 更多<a-icon type="down" /> </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a-button type="link" @click="gotoDetail(record)" size="small">详情</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="couponSend(record)" size="small">发放</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="clickQrcode(record.id)" size="small">小程序二维码</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-popconfirm title="确认删除该优惠券吗？" placement="left" @confirm="handleDelete(record)">
                <a-button type="link" size="small">删除</a-button>
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>
    <!-- 创建优惠券 -->
    <a-modal
      :title="isNew ? '创建优惠券' : '编辑优惠券'"
      :width="800"
      :confirm-loading="modalLoading"
      :mask-closable="false"
      :destroy-on-close="true"
      :bodyStyle="{ height: '600px', overflow: 'auto' }"
      v-model="visible"
      @ok="handleOk"
    >
      <a-form class="permission-form" :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="display: none" label="主键" hasFeedback>
          <a-input placeholder="主键" :disabled="!isNew" v-decorator="['id']" />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠券名称" hasFeedback>
          <a-input
            placeholder="优惠券名称"
            v-decorator="['name', { rules: [{ required: true, message: '请填写优惠券名称' }] }]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠券类型" extra="">
          <a-radio-group
            v-decorator="[
              'discount_type',
              {
                initialValue: 2,
                getValueFromEvent: e => {
                  this.show_status.discount_type = e.target.value
                  return e.target.value
                }
              }
            ]"
          >
            <a-radio :value="2"> 满减券 </a-radio>
            <a-radio :value="1"> 折扣券 </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          :class="show_status.discount_type == 2 ? '' : 'hide'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="优惠金额"
          extra="优惠券只能抵消商品金额，不能抵消运费，商品金额最多优惠到0.01元"
        >
          <a-input-number
            placeholder="优惠金额"
            :formatter="value => `${value}元`"
            :parser="value => value.replace('元', '')"
            :min="0"
            :precision="2"
            :step="0.01"
            v-decorator="['sub_price', { initialValue: 0 }]"
          />
        </a-form-item>

        <a-form-item
          :class="show_status.discount_type == 1 ? '' : 'hide'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="折扣率"
          extra="如打8.5折请填写8.5，如不打折请填写10
支持折扣率0.1-10"
        >
          <a-input-number
            placeholder="折扣率"
            :formatter="value => `${value}折`"
            :parser="value => value.replace('折', '')"
            :min="0"
            :max="10"
            :precision="1"
            :step="0.1"
            v-decorator="['discount', { initialValue: 10 }]"
          />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="最低消费金额"
          extra="购物金额（不含运费）达到最低消费金额才可使用优惠券，无门槛优惠券请填0"
        >
          <a-input-number
            placeholder="最低消费金额"
            :formatter="value => `${value}元`"
            :parser="value => value.replace('元', '')"
            :min="0"
            :precision="2"
            :step="0.01"
            v-decorator="['min_price', { initialValue: 0, rules: [{ required: true, message: '请填写最低消费金额' }] }]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="到期类型" extra="">
          <a-radio-group
            v-decorator="[
              'expire_type',
              {
                initialValue: 1,
                getValueFromEvent: e => {
                  this.show_status.expire_type = e.target.value
                  return e.target.value
                }
              }
            ]"
          >
            <a-radio :value="1"> 领取后N天内有效 </a-radio>
            <a-radio :value="2"> 时间段 </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          :class="show_status.expire_type == 1 ? '' : 'hide'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="有效天数"
        >
          <a-input-number placeholder="有效天数" :min="0" v-decorator="['expire_day', { initialValue: 0 }]" />
        </a-form-item>

        <a-form-item
          :class="show_status.expire_type == 2 ? '' : 'hide'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="有效期范围"
        >
          <a-range-picker
            :format="'YYYY-MM-DD'"
            :valueFormat="'YYYY-MM-DD'"
            v-decorator="['expire_date', [{ type: 'array' }]]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否可线上领取" extra="">
          <a-radio-group
            v-decorator="[
              'is_join',
              {
                initialValue: 2,
                getValueFromEvent: e => {
                  this.show_status.is_join = e.target.value
                  return e.target.value
                }
              }
            ]"
          >
            <a-radio :value="1"> 否 </a-radio>
            <a-radio :value="2"> 是 </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          v-if="this.is_saas"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="加入SAAS福利中心"
          extra=""
        >
          <a-radio-group
            v-decorator="[
              'is_join_welfare',
              {
                initialValue: 0,
                getValueFromEvent: e => {
                  this.show_status.is_join_welfare = e.target.value
                  return e.target.value
                }
              }
            ]"
          >
            <a-radio :value="0"> 不加入 </a-radio>
            <a-radio :value="1"> 加入 </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          :class="show_status.is_join == 2 ? '' : 'hide'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="发放总数"
          help="发放总数为-1，表示不限制发放数量"
        >
          <a-input-number placeholder="发放总数" :min="-1" v-decorator="['total_count', { initialValue: -1 }]" />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input-number placeholder="排序" :min="0" v-decorator="['sort', { initialValue: 0 }]" />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="指定类型" extra="">
          <a-radio-group
            v-decorator="[
              'appoint_type',
              {
                initialValue: 1,
                getValueFromEvent: e => {
                  this.show_status.appoint_type = e.target.value
                  return e.target.value
                }
              }
            ]"
          >
            <a-radio :value="1"> 商品类别 </a-radio>
            <a-radio :value="2"> 商品 </a-radio>
            <!-- <a-radio :value="3"> 当面付 </a-radio> -->
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :class="show_status.appoint_type == 1 ? '' : 'hide'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="商品类别"
          extra="不添加表示全场通用"
        >
          <a-input-search
            @search="selectGoodsCatModal"
            placeholder="商品类别"
            :readOnly="true"
            v-decorator="['cat_name_list']"
          >
            <a-button @click="selectGoodsCatModal" slot="enterButton">选择类别</a-button>
          </a-input-search>
          <div
            v-if="cat_list && cat_list.length > 0 && show_status.appoint_type == 2"
            class="chhhhhhhh"
            style="width: 100%"
          >
            <div style="float: left; width: 60px; margin: 5px 10px" v-for="(item, index) in cat_list" :key="index">
              <div style="width: 100%; height: 60px">
                <img width="100%" height="100%" :src="item.pic_url" alt="" />
              </div>
              <div style="width: 100%; text-align: center">{{ item.name }}</div>
            </div>
          </div>
        </a-form-item>
        <a-form-item
          :class="show_status.appoint_type == 2 ? '' : 'hide'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="添加商品"
          extra="不添加表示全场通用"
        >
          <a-input-search
            @search="selectGoodsModal"
            placeholder="选择商品"
            :readOnly="true"
            v-decorator="['goods_id_list']"
          >
            <a-button @click="selectGoodsModal" slot="enterButton">选择商品</a-button>
          </a-input-search>
          <div v-if="goods_list && goods_list.length > 0" style="width: 100%">
            <div style="float: left; width: 60px; margin: 5px 10px" v-for="(item, index) in goods_list" :key="index">
              <div style="width: 100%; height: 60px">
                <img width="100%" height="100%" :src="item.cover_pic" alt="" />
              </div>
              <div style="width: 100%; text-align: center; overflow: hidden; height: 40px">{{ item.name }}</div>
            </div>
          </div>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否可转赠：" extra="">
          <a-radio-group
            v-decorator="[
              'is_give',
              {
                initialValue: '0'
              }
            ]"
          >
            <a-radio value="1"> 是 </a-radio>
            <a-radio value="0"> 否 </a-radio>
          </a-radio-group>
          <p style="font-size: 14px; line-height: 22px; color: rgba(0, 0, 0, 0.85); opacity: 0.45">
            如果选择是，用户获得优惠券后，可以将优惠券转增分享给好友，好友打开链接后， 如好友是新用户可绑定上下级关系
          </p>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="使用说明">
          <a-textarea
            :rows="2"
            id="rule"
            v-decorator="['rule', { rules: [{ required: true, message: '请输入使用说明' }] }]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <SelectCat v-model="select_cat_visible" @onOk="selectGoodsCatOk"></SelectCat>
    <SelectGoods v-model="select_goods_visible" @onOk="selectGoodsOk"></SelectGoods>
    <!-- 发放优惠券给用户 -->
    <a-modal
      :title="'发放优惠券'"
      :width="800"
      :confirm-loading="modalLoading"
      :mask-closable="false"
      :destroy-on-close="true"
      :bodyStyle="{ 'max-height': '600px', overflow: 'auto' }"
      v-model="send_visible"
      @ok="send_handleOk"
    >
      <a-form class="permission-form" :form="send_form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠券名称" extra="">
          <span style="padding-left: 20px">{{ send_data.name }}</span>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="最低消费金额" extra="">
          <span style="padding-left: 20px">{{ send_data.min_price }}</span>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="优惠金额"
          extra=""
          v-if="send_data.discount_type == 2"
        >
          <span style="padding-left: 20px">{{ send_data.sub_price }}</span>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠折扣" extra="" v-else>
          <span style="padding-left: 20px">{{ send_data.discount }}折</span>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="剩余数量" extra="">
          <span style="padding-left: 20px" v-if="send_data.surplus_count != -1">{{ send_data.surplus_count }}</span>
          <span style="padding-left: 20px" v-else>无限制</span>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠券有效期" extra="">
          <span style="padding-left: 20px" v-if="send_data.expire_type == 1 && send_data.expire_day > 0"
            >领取后{{ send_data.expire_day }}天有效</span
          >
          <span style="padding-left: 20px" v-if="send_data.expire_type == 1 && send_data.expire_day == 0"
            >永久有效</span
          >
          <span style="padding-left: 20px" v-if="send_data.expire_type == 2"
            >{{ send_data.begin_time }} ~ {{ send_data.end_time }}</span
          >
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发放对象" extra="">
          <select-user @userInfo="getInfo" :defaultUser="user_id" dataType="single" returnType="id" selectType="user">
          </select-user>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal title="小程序二维码" :visible="showQrCode" @ok="downloadQrCode" @cancel="showQrCode = false">
      <div style="display: flex; justify-content: center">
        <img style="width: 300px; height: 300px" :src="this.qrcodeUrl" alt="" />
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import pick from 'lodash.pick'
import { STable } from '@/components'
// import SelectCat from './components/selectGoodsCat'
import SelectCat from '@/components/SearchCat/index'
import SelectGoods from '@/components/SearchGoods/index'
import SelectUser from '@/components/SelectUser/SelectUser1'
import { getPermission } from '@/api/auth'
import {
  couponList,
  couponDel,
  couponAdd,
  couponEdit,
  couponSendUser,
  couponDels,
  couponStatus,
  couponQrcode
} from '@/api/marketing'

const STATUS = {
  1: '显示',
  0: '不显示'
}

const columns = [
  {
    title: '优惠券ID',
    dataIndex: 'id'
  },
  {
    title: '优惠券名称',
    dataIndex: 'name'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at'
  },
  {
    title: '最低消费',
    dataIndex: 'min_price',
    scopedSlots: {
      customRender: 'min_price'
    },
    sorter: (a, b) => a.min_price - b.min_price
  },
  {
    title: '优惠方式',
    dataIndex: 'discount_type_text',
    scopedSlots: {
      customRender: 'discount_type_text'
    }
  },
  {
    title: '优惠券金额',
    dataIndex: 'sub_price',
    scopedSlots: {
      customRender: 'sub_price'
    },
    sorter: (a, b) => a.sub_price - b.sub_price
  },
  {
    title: '折扣率',
    dataIndex: 'discount',
    scopedSlots: {
      customRender: 'discount'
    },
    sorter: (a, b) => a.discount - b.discount
  },
  {
    title: '已领',
    dataIndex: 'total_count',
    scopedSlots: {
      customRender: 'total_count'
    },
    // 总数减剩余为已领   剩余默认是-1  总数默认是 -1
    sorter: (a, b) => a.total_count - a.surplus_count - (b.total_count - b.surplus_count)
  },
  {
    title: '剩余',
    dataIndex: 'surplus_count',
    scopedSlots: {
      customRender: 'surplus_count'
    },
    sorter: (a, b) => a.surplus_count - b.surplus_count
  },

  {
    title: '有效时间',
    dataIndex: 'expire_type',
    scopedSlots: {
      customRender: 'expire_type'
    }
  },
  {
    title: '状态',
    dataIndex: 'coupon_status',
    scopedSlots: {
      customRender: 'coupon_status'
    }
  },
  {
    title: '领券中心',
    dataIndex: 'is_join',
    scopedSlots: {
      customRender: 'is_join'
    }
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action'
    }
  }
]

export default {
  name: 'ArticleList',
  components: {
    STable,
    SelectCat,
    SelectGoods,
    SelectUser
  },
  data() {
    return {
      is_saas: false,
      user_id: '',
      isNew: false,
      visible: false,
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 5
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        }
      },
      form: this.$form.createForm(this),
      // 表单数据
      formData: {
        cat_id_list: [],
        cat_name_list: ''
      },
      cat_list: [],
      goods_list: [],
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      // 已选择的权限
      selectedPermission: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: {
        key: '1',
        label: '显示'
      },
      type_list: [],
      show_status: {
        discount_type: 2,
        expire_type: 1,
        is_join: 2,
        is_integral: 1,
        appoint_type: 1
      },
      send_visible: false,
      send_data: {},
      send_form: this.$form.createForm(this),
      // 查询条件参数
      queryParam: {
        search_key: null,
        status: -1
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        Object.assign(parameter, this.queryParam)
        console.log(parameter, 'parameter')
        return couponList(parameter)
          .then(res => {
            console.log('couponList', res)
            this.type_list = res.data.type_list
            this.is_saas = res.data.is_join_saas == 1
            return res.data
          })
          .catch(err => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },

      // 选择分类开始
      select_cat_visible: false,
      select_goods_visible: false,
      // 选择分类结束
      selectedRowKeys: [],
      tabIndex: 1,

      activeTab: '1',
      showQrCode: false,
      qrcodeUrl: '',
      sendRule: ''
    }
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    }
  },
  created() {
    getPermission({}).then(res => {
      this.permissionTree = res.data
    })
  },
  props: {
    search: {
      type: String,
      default: ''
    }
  },
  watch: {
    search(val) {
      console.log('搜索的阿萨德科技', val)
      this.queryParam.search_key = val
    }
  },
  methods: {
    moment,
    reload() {
      this.$refs.table.refresh()
    },
    downloadQrCode() {
      const src =
        'http://chidian.cyyvip.com/web/uploads/images/store_1/2021-12-01/29661223524c20e781af568c944f90e49b547258.jpg'
      this.getCanvasBase64(src, e => {
        console.log(e)
        const link = document.createElement('a') // 创建a标签
        link.style.display = 'none'
        link.href = e

        link.setAttribute('download', '') // 添加downLoad属性
        document.body.appendChild(link)
        link.click()
      })
    },
    getCanvasBase64(img, cb) {
      var image = new Image()
      // 至关重要
      image.crossOrigin = ''
      image.src = img
      if (img) {
        image.onload = () => {
          const data = this.getBase64Image(image) // 将base64传给done上传处理
          console.log(data)
          cb && cb(data)
        }
      }
    },
    getBase64Image(img) {
      var canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      var ctx = canvas.getContext('2d')
      const imgNode = new Image()
      imgNode.src = img
      imgNode.onload = function(e) {
        console.log('图片load好了没', e)
        ctx.drawImage(imgNode, 0, 0, canvas.width, canvas.height)
        var dataURL = canvas.toDataURL()
        console.log(dataURL)
        return dataURL
      }
    },
    gotoDetail(item) {
      console.log(item)
      this.$router.push({ name: 'CouponDetail', query: { id: item.id } })
    },
    // 选择商品分类弹窗
    selectGoodsCatModal() {
      this.select_cat_visible = !this.select_cat_visible
    },
    selectGoodsCatOk(e) {
      console.log(e)
      this.cat_list = e
      this.$nextTick(() => {
        this.form.setFieldsValue({
          cat_id_list: JSON.stringify(e.map(el => el.id))
        })
        this.form.setFieldsValue({
          cat_name_list: e.map(el => el.name).join()
        })
      })
      // this.selectGoodsCatModal()
    },
    selectGoodsModal() {
      this.select_goods_visible = !this.select_goods_visible
    },
    selectGoodsOk(e) {
      console.log(e)
      var id = []
      for (var i in e) {
        id.push(parseInt(e[i].id))
      }
      this.goods_list = e
      this.$nextTick(() => {
        this.form.setFieldsValue({
          goods_id_list: JSON.stringify(id)
        })
      })
    },
    changeShow(item) {
      console.log(item)
      const hide = this.$message.loading('请求中...', 0)
      couponEdit({
        key: item.id,
        is_show: item.is_show
      })
        .then(res => {
          hide()
          if (res.code === 0) {
            this.$message.success('操作成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg
            })
          }
        })
        .catch(err => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      record.discount_type = parseInt(record.discount_type)
      record.expire_type = parseInt(record.expire_type)
      record.is_join = parseInt(record.is_join)
      record.is_join_welfare = parseInt(record.is_join_welfare)
      record.is_integral = parseInt(record.is_integral)
      record.appoint_type = parseInt(record.appoint_type)
      this.cat_list = record.cat_list
      this.goods_list = record.goods_list
      Object.assign(this.show_status, {
        discount_type: record.discount_type,
        expire_type: record.expire_type,
        is_join: record.is_join,
        is_join_welfare: record.is_join_welfare,
        is_integral: record.is_integral,
        appoint_type: record.appoint_type
      })
      this.$nextTick(() => {
        if (record.expire_type == 2) {
          record.expire_date = [record.begin_time, record.end_time]
        }
        this.form.setFieldsValue({
          cat_name_list: record.cat_list.map(el => el.name).join()
        })
        this.form.setFieldsValue(
          pick(record, [
            'id',
            'name',
            'discount_type',
            'sub_price',
            'discount',
            'min_price',
            'expire_type',
            'expire_day',
            'expire_date',
            'is_join',
            'total_count',
            'sort',
            'appoint_type',
            'cat_id_list',
            'goods_id_list',
            'rule',
            'is_join_welfare',
            'is_give'
          ])
        )
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        if (values.expire_date && values.expire_date.length > 0) {
          values.begin_time = values.expire_date[0]
          values.end_time = values.expire_date[1]
        }
        this.modalLoading = true
        if (this.isNew) {
          couponAdd({ ...values, cat_id_list: JSON.stringify(this.cat_list.map(item => item.id)) })
            .then(res => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg
                })
              } else {
                this.$message.success('优惠券创建成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch(err => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        } else {
          couponEdit({ ...values, cat_id_list: JSON.stringify(this.cat_list.map(item => item.id)) })
            .then(res => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg
                })
              } else {
                this.$message.success('优惠券编辑成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch(err => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    onAdd: function() {
      this.isNew = true
      this.visible = true
      this.defaultCheckedKeys = []
      this.cat_list = []
      this.goods_list = []
      this.show_status = {
        discount_type: 2,
        expire_type: 1,
        is_join: 2,
        is_integral: 1,
        appoint_type: 1
      }
    },
    couponSend(item) {
      console.log(item)
      this.send_visible = true
      this.send_data = item
    },
    send_handleOk(e) {
      e.preventDefault()
      this.send_form.validateFields((err, values) => {
        if (err) {
          return false
        }
        values.coupon_id = this.send_data.id
        values.user_id = this.user_id
        this.modalLoading = true
        couponSendUser(values)
          .then(res => {
            console.log(res)
            this.modalLoading = false
            if (res.code !== 0) {
              this.$error({
                content: res.msg
              })
            } else {
              this.$message.success('优惠券发放成功！')
              this.send_visible = false
              this.$refs.table.refresh()
            }
          })
          .catch(err => {
            this.$message.error(err.message)
            this.modalLoading = false
          })
      })
    },
    handleDelete: function(record) {
      const hide = this.$message.loading('删除中...', 0)
      couponDel({
        key: record.id
      })
        .then(res => {
          hide()
          if (res.code === 0) {
            this.$message.success('优惠券删除成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg
            })
          }
        })
        .catch(err => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_key: null
      })
      this.$refs.table.refresh(true)
    },
    getInfo(val) {
      console.log(val)
      this.user_id = val
    },
    // 开关变换
    async switchChange(val, item) {
      console.log(val, item, '更改优惠券加入领卷中心状态')
      try {
        const res = await couponStatus({ is_join: val ? 2 : 1, id: item.id })
        if (res.code != 0) throw res
        this.$refs.table.refresh()
        this.$message.success(res.msg)
      } catch (error) {
        this.$message.error(res.msg || '服务器出错')
      }
    },
    // 表格选中变化
    onSelectChange(data) {
      console.log(data)
      console.log('this.selectedRowKeys :>> ', this.selectedRowKeys)
      this.selectedRowKeys = data
    },
    // tab变化
    clickTab({ target: { value: val } }) {
      this.selectedRowKeys = []
      this.queryParam.status = val
      this.$refs.table.refresh()
    },
    // 批量操作
    async handleMenuClick() {
      if (!this.selectedRowKeys.length) return
      try {
        const res = await couponDels({ id: this.selectedRowKeys, status: 1 })
        if (res.code != 0) throw res
        this.selectedRowKeys = []
        this.$refs.table.refresh()
        this.$message.success(res.msg)
      } catch (res) {
        this.$message.error(res.msg || '服务器出错')
      }
    },
    // 显示小程序二维码
    async clickQrcode(id) {
      const res = await couponQrcode({ key: id })
      if (res.code != 0) return
      this.qrcodeUrl = res.data
      this.showQrCode = !this.showQrCode
    }
  }
}
</script>

<style lang="less" scoped>
// 优惠券状态样式
.coupon-status-1,
.coupon-status-2,
.coupon-status-3 {
  &::before {
    content: '';
    display: inline-block;
    width: 6px;
    height: 6px;
    background: #1890ff;
    border-radius: 50%;
    margin-right: 8px;
    transform: translateY(-2px);
  }
}
.coupon-status-2 {
  &::before {
    background: #c6c6c6;
  }
}
.coupon-status-3 {
  &::before {
    background: #faad14;
  }
}

.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.hide {
  display: none;
}
</style>
